package com.octopus.media;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;

import com.octopus.media.fuwu.Monitoring;
import com.octopus.media.fuwu.SocketServer;
import com.octopus.media.fuwu.VideoProvide;
import com.octopus.media.view.FullScreenVideoView;

public class MainActivity extends AppCompatActivity {

    private FullScreenVideoView videoView ;
    private int pauseTime = 0;
    private boolean isHome = false;

    class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Intent sendMsg = new Intent("com.media.getBendiUrl");
            sendBroadcast(sendMsg);
        }
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent ==null ) return;
            String videoUrl = intent.getStringExtra("URL");
            if (videoUrl == null || videoUrl.equals("")) return;
            Uri uri = Uri.parse(videoUrl);
            if (videoView.isPlaying()){
                videoView.stopPlayback();
            }
            videoView.setVideoURI(uri);
            isHome = false;
            pauseTime = 0;
            //开始播放视频
            videoView.start();
        }
    };



    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindow();

        setContentView(R.layout.activity_main);

        keepScreenOn(getApplicationContext(),true);

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.media.sendBendiUrl");
        registerReceiver(myReceiver, filter);

        Intent intentVideoProvide = new Intent(getApplication(), VideoProvide.class);
        startService(intentVideoProvide);
        Intent intentScoket= new Intent(getApplication(), SocketServer.class);
        startService(intentScoket);

        initView();

        startFirst();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intentMonitoring= new Intent(getApplication(), Monitoring.class);
        bindService(intentMonitoring, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (isHome && videoView!=null){
            videoView.seekTo(pauseTime);
            videoView.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView!=null){
            pauseTime = videoView.getCurrentPosition();
            videoView.pause();
            Log.i("pauseTime",pauseTime+"");
            isHome = true;
        }
    }

    private void setWindow(){
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
    }

    private void initView(){
        videoView = findViewById(R.id.videoView);
        //设置视频控制器
        MediaController mediaCtlr = new MediaController(this);
        mediaCtlr.setVisibility(View.INVISIBLE); //设置隐藏
        videoView.setMediaController(mediaCtlr);

        //播放完成回调
        videoView.setOnCompletionListener( new MyPlayerOnCompletionListener());
    }

    private void startFirst(){
        new Handler().postDelayed(new Runnable(){
            public void run() {
                Intent sendMsg = new Intent("com.media.getBendiUrl");
                sendBroadcast(sendMsg);
            }
        }, 2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        keepScreenOn(getParent(),false);

        unregisterReceiver(myReceiver);
    }

    private PowerManager.WakeLock wakeLock;
    @SuppressLint("InvalidWakeLockTag")
    public void keepScreenOn(Context context, boolean on) {
        if (on) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "==KeepScreenOn==");
            wakeLock.acquire();
        } else {
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
        }
    }

    Monitoring mService;
    boolean mBound = false;
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            Monitoring.MonitoringBinder binder = (Monitoring.MonitoringBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

}
